package com.facebookproject.loginfb;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

public class LoginFacebook {
	String FILENAME = "FacebookProject_Data";
	private SharedPreferences mPrefs;
	String[] permission = {
			"email",
			"publish_stream",
			"user_photos",
			"user_events",
			"user_likes",
			"user_relationships",
			"user_about_me",
			"user_education_history",
			"user_work_history",
			"user_birthday",
			"user_relationship_details",
			"user_location",
			"user_birthday",
			"user_hometown",
			"user_questions",
			"user_website",
			"read_friendlists",
			"friends_photos",
			"friends_about_me",
			"friends_education_history",
			"friends_relationships",
			"friends_work_history",
			"friends_hometown",
			"friends_location",
			"friends_events",
			"friends_relationship_details",
			"friends_about_me",
	"friends_birthday"};

	@SuppressWarnings("deprecation")
	public Facebook login(final Context context, final Facebook facebook) {
		
			mPrefs = context.getSharedPreferences(FILENAME, 0);
			String access_token = mPrefs.getString("access_token", null);
			long expires = mPrefs.getLong("access_expires", 0);
			
			if (access_token != null) {
				facebook.setAccessToken(access_token);
				Log.d("FB Sessions", "" + facebook.isSessionValid());
			}
			if (expires != 0) {
				facebook.setAccessExpires(expires);
			}
			if (!facebook.isSessionValid()) {
				facebook.authorize((Activity) context,
						permission,
						new DialogListener() {
					@Override
					public void onCancel() {
						Toast.makeText(context,"Error: Facebook login is cancel",Toast.LENGTH_LONG).show();
					}
					@Override
					public void onComplete(Bundle values) {
						Editor editor = mPrefs.edit();
						editor.putString("access_token", facebook.getAccessToken());
						editor.putLong("access_expires", facebook.getAccessExpires());
						editor.commit();
					}
					@Override
					public void onError(DialogError error) {
						Toast.makeText(context,"Error: onError",Toast.LENGTH_LONG).show();
					}
					@Override
					public void onFacebookError(FacebookError fberror) {
						Toast.makeText(context,"Error: onFacebookError",Toast.LENGTH_LONG).show();
					}
				});
			}
		
		return facebook;
	}


}
